<?php
if (!defined('admin')) {
    exit();
}
if (power('alevel') != 3) {
    die('error');
}
if (isset($_POST['submit'])) {
    checktoken();
    $newurl = array();
    $controller = array();
    foreach ($_POST['diyurl'] as $key => $val) {
        if (!empty($_POST['diyurl'][$key])) {
            $diyurltemplate = postroutercheck($_POST['diyurltemplate'][$key]);
            $newurl[] = array('method' => dbstr($_POST['diymethod'][$key]), 'uri' => postroutercheck($_POST['diyurl'][$key], 1), 'res' => $diyurltemplate, 'cache' => intval($_POST['diyurlcache'][$key]), 'domain' => $_POST['diydomain'][$key]);
            if (strpos($diyurltemplate, ';') !== false) {
                $con_arr = explode(';', $diyurltemplate);
                foreach ($con_arr as $item) {
                    $controller[] = $item;
                }
            } else {
                $controller[] = $diyurltemplate;
            }
        }
    }


    $newurl = dbstr(json_encode($newurl));
    $allurl = M()->one("SELECT * FROM " . tableex('str') . " where strname='diyurl' and inputkind=0 limit 1;");
    if (!$allurl) {
        $query = M()->query("INSERT INTO `" . tableex('str') . "` (`strname`,`strcid`,`strorder`,`inputkind`,`strvalue`,`ifadmin`) VALUES ('diyurl','0','0','0','$newurl','1');");
    } else {
        $query = M()->query("UPDATE " . tableex('str') . " SET strvalue='$newurl' WHERE strname='diyurl' and inputkind=0;");
    }
    if ($query) {
        channelrouter();

        createController($controller);

        adminmsg('?do=sadmin_url', '保存成功', 3);
    } else {
        adminmsg('?do=sadmin_url', '保存失败', 3);
    }
}
$allurl = M()->one("SELECT * FROM " . tableex('str') . " where strname='diyurl' and inputkind=0 limit 1;");
if ($allurl) {
    $allurl = json_decode($allurl['strvalue'], 1);
}
if (!$allurl) {
    $allurl = array();
}

?>
    <style>
        .move {
            display: inline-block;
            width: 15px;
            font-size: 12px;
            position: relative;
            left: -4px;
            top: -4px;
            float: left;
        }

        .move a {
            display: block;

        }
    </style>
<?php admin_page_start('路由') ?>
    <h3>
        <a style="margin-left:10px" href="?do=sadmin" class="actionBtn">返回</a>
        路由配置
    </h3>
    <div style="text-align: center;margin: 10px">
        <p>控制器：填写格式可以是【控制器类@方法】和【文件名.php】，控制器文件存放在application/controller中</p>
        <p>匹配顺序：根据从上往下的顺序匹配，越宽泛的路由规则应放在越下面</p>
        <p>域名：为空则任意域名可访问，使用;隔开多个域名，一旦绑定了域名，仅绑定的域名可访问此路由</p>
        <p>保存并创建：根据设定的控制器在控制器目录中创建对应的文件及方法，但参数需要自己编辑</p>
    </div>
    <form id="form1" class="nowidth100p_form" method="post" action="?do=sadmin_url">
        <input type="hidden" size="35" name="submit" value="1">
        <input id="create" type="hidden" size="35" name="create" value="1">
        <?php newtoken(); ?>
        <table border="0" cellpadding="8" cellspacing="0" class="tablerowtip" align=center>
            <?php
            foreach ($allurl as $key => $val) {
                !isset($val['method']) and $val['method'] = 'all';
                ?>
                <tr>
                    <td>
                        <div class="move">
                            <a href="javascript:" onclick="moveTr(this,'up')">⬆</a>
                            <a href="javascript:" onclick="moveTr(this,'down')">⬇</a>
                        </div>
                        <label>请求: <select name="diymethod[]" class="inputtext">
                                <option value="all" <?php echo($val['method'] == 'all' ? 'selected="selected"' : ''); ?> >
                                    ALL
                                </option>
                                <option value="get" <?php echo($val['method'] == 'get' ? 'selected="selected"' : ''); ?>>
                                    GET
                                </option>
                                <option value="post" <?php echo($val['method'] == 'post' ? 'selected="selected"' : ''); ?>>
                                    POST
                                </option>
                                <option value="put" <?php echo($val['method'] == 'put' ? 'selected="selected"' : ''); ?>>
                                    PUT
                                </option>
                                <option value="delete" <?php echo($val['method'] == 'delete' ? 'selected="selected"' : ''); ?>>
                                    DELETE
                                </option>
                            </select></label>
                        <label>域名: <input class="inputtext" type="text" size="20" name="diydomain[]"
                                          value="<?php if (isset($val['domain'])) echo($val['domain']); ?>">
                        </label><label>地址: <input class="inputtext" type="text" size="20" name="diyurl[]"
                                          value="<?php echo($val['uri']); ?>"></label>

                        &nbsp;&nbsp;&nbsp;&nbsp;<label>缓存时间: <input class="inputtext" type="text" size="5"
                                                                    name="diyurlcache[]"
                                                                    value="<?php echo($val['cache']); ?>">
                            <i>秒</i></label>
                        <label>&nbsp;&nbsp;&nbsp;控制器: <input class="inputtext" type="text" size="30"
                                                            name="diyurltemplate[]"
                                                            value="<?php echo($val['res']); ?>"></label>
                        <a href="javascript:" class="delthispage">删除</a>
                    </td>
                </tr>
                <?php
            }
            ?>


            <tr class="addurltr">
                <td>
                    <a href="javascript:" class="add_urltr" style="color:#FF6600">[+]增加</a>


                    <input type="submit" id="savebutton" value="保存" class="btn  btn-primary"
                           style="float:right;margin-right:10px;">
                </td>
            </tr>

        </table>
    </form>

    <table id="newurlhtml" style="display:none">
        <tr class="new_urltr">
            <td>
                <div class="move">
                    <a href="javascript:" onclick="moveTr(this,'up')">⬆</a>
                    <a href="javascript:" onclick="moveTr(this,'down')">⬇</a>
                </div>
                <label>请求: <select name="diymethod[]" class="inputtext">
                        <option value="all">ALL</option>
                        <option value="get">GET</option>
                        <option value="post">POST</option>
                        <option value="put">PUT</option>
                        <option value="delete">DELETE</option>
                    </select></label>
                <label>域名: <input class="inputtext" type="text" size="20" name="diydomain[]" value=""></label>
                <label>地址: <input class="inputtext" type="text" size="35" name="diyurl[]" value=""></label>
                <label>缓存时间: <input class="inputtext" type="text" size="5" name="diyurlcache[]" value="0"> <i>秒</i></label>
                <label>&nbsp;&nbsp;&nbsp;文件: <input class="inputtext" type="text" size="30" name="diyurltemplate[]" value=""></label>
                <a href="javascript:" class="delthispage">删除</a>
            </td>
        </tr>
    </table>

    <script type="text/javascript">

        /*
        params
        t:触发事件的元素
        oper:操作方式
    */
        function moveTr(t, oper) {
            var data_tr = $(t).closest("tr"); //获取到触发的tr
            if (oper === "up") {    //向上移动
                if ($(data_tr).prev().html() == null) { //获取tr的前一个相同等级的元素是否为空
                    // alert("已经是最顶部了!");
                    return;
                }
                {
                    $(data_tr).insertBefore($(data_tr).prev()); //将本身插入到目标tr的前面
                }
            } else {
                if ($(data_tr).next().hasClass("addurltr")) {
                    return;
                }
                if ($(data_tr).next().html() == null) {
                    // alert("已经是最低部了!");
                    return;
                }
                {
                    $(data_tr).insertAfter($(data_tr).next()); //将本身插入到目标tr的后面
                }
            }
        }

        $("#save_create_button").click(function () {
            $("#create").val(1);
            return true;
        });

        $(function () {
            $(function () {
                $('.add_urltr').click(quick_add_str);

                function quick_add_str() {
                    $('.addurltr').before('<tr class="new_urltr">' + $('#newurlhtml tr').html() + '</tr>');
                }
            });
            $('.addotherpage').click(function () {
                $('#otherpage').append($('#newotherpage').html());
            });

            $(document).on('click', '.delthispage', function () {
                $(this).parent().remove();
            });


        });
    </script>
<?php admin_page_end();